/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.logadaptor.impl;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.LogManager;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;

import com.cqcis.uip.base.logadaptor.LoggerAppenderRepository;

/**
 * @author huangmy
 * @date 2008-1-31
 */
@SuppressWarnings("unchecked")
public class Log4jLoggerFactory implements ILoggerFactory {
	private Map<String, Log4jLoggerAdapter> loggerMap = new HashMap<String, Log4jLoggerAdapter>();
	private LoggerAppenderRepository ar = LoggerAppenderRepositoryImpl.getLoggerAppenderRepository();
    
	private static List<FileAppender> rootFileAppenders = new ArrayList<FileAppender>();
	private static List<Appender> rootOtherAppenders = new ArrayList<Appender>();
	
	static {
		org.apache.log4j.Logger root = LogManager.getRootLogger();		
		Enumeration<Appender> appenders = root.getAllAppenders();
				
		if (appenders != null) {
			while (appenders.hasMoreElements()) {
				Appender a = appenders.nextElement();
				
				if (a instanceof FileAppender) {					
					rootFileAppenders.add((FileAppender)a);					
				} else {
					rootOtherAppenders.add(a);
				}
			}
		}
	}
        
	public Logger getLogger(String name) {
		Log4jLoggerAdapter slf4jLogger = null;
		
		synchronized (loggerMap) {
			slf4jLogger = loggerMap.get(name);
			if (slf4jLogger == null) {
				org.apache.log4j.Logger log4jLogger = null;
				
				if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME)) {
					log4jLogger = LogManager.getRootLogger();
				} else {
					log4jLogger = LogManager.getLogger(name);
				}
								
				slf4jLogger = new Log4jLoggerAdapter(log4jLogger);
				slf4jLogger.setAr(ar);
								
				loggerMap.put(name, slf4jLogger);
			}
		}

		return slf4jLogger;
	}
}
